package com.wxl.config;


import com.wxl.util.ZkWorkerIdManager;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ZkConfig {

    @Value("${zk.address:localhost:2181}")
    private String zkAddress;

    @Value("${server.port:8080}")
    private int serverPort;

    @Bean(destroyMethod = "close")
    public CuratorFramework curatorFramework() {
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(zkAddress)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        client.start();
        return client;
    }

    @Bean
    public ZkWorkerIdManager zkWorkerIdManager(CuratorFramework client) throws Exception {
        String ip = java.net.InetAddress.getLocalHost().getHostAddress();
        String ipPort = ip + ":" + serverPort;
        return new ZkWorkerIdManager(client, ipPort);
    }
}